/*
 * @Author: xym100111100 253274870@qq.com
 * @Date: 2024-03-19 10:23:53
 * @LastEditors: xym100111100 253274870@qq.com
 * @LastEditTime: 2024-08-21 21:16:44
 * @FilePath: \RuoYi-Vue3\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { login as logins, logout, getInfo as getInfos, type LoginReq  } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'



 const useUserStore = defineStore('user', () => {

  const token = ref(getToken())
  const id = ref("")
  const name = ref("")
  const avatar = ref("")
  const roles =  ref<string[]>([])
  const permissions = ref<string[]>([])

function  login(userInfo:LoginReq) { 
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return new Promise<void>((resolve, reject) => {
      logins(username, password, code, uuid).then(res => {
        setToken(res.token)
        token.value = res.token
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }


  function getInfo() {
    return new Promise((resolve, reject) => {
      getInfos().then(res => {
        const user = res.user
        
        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = res.roles
          permissions.value = res.permissions
        } else {
          roles.value = ['ROLE_DEFAULT']
        }
        id.value = user.userId
        name.value = user.userName
        avatar.value =(user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }


  function logOut() {
    return new Promise<void>((resolve, reject) => {
      logout().then(() => {
        token.value = ''
        roles.value = []
        permissions.value = []
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }


 



  return {token,id,name,avatar,roles,login,permissions, getInfo,logOut}
})


export default useUserStore